package com.jz.community.moduleshoppingguide.home.ui.activity;

import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.gyf.barlibrary.ImmersionBar;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.bean.RegionsBean;
import com.jz.community.basecomm.glideConfig.GlideApp;
import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.commview.callback.EmptyCallback;
import com.jz.community.commview.callback.ErrorCallback;
import com.jz.community.commview.callback.LoadingCallback;
import com.jz.community.commview.view.CardLoadMoreView;
import com.jz.community.moduleshoppingguide.R;
import com.jz.community.moduleshoppingguide.R2;
import com.jz.community.moduleshoppingguide.home.bean.CategoriesGoodsBean;
import com.jz.community.moduleshoppingguide.home.bean.ChunnelTypeBean;
import com.jz.community.moduleshoppingguide.home.presenter.ChannelOutPresenter;
import com.jz.community.moduleshoppingguide.home.ui.adapter.OutGoodsTypeAdapter;
import com.jz.community.moduleshoppingguide.home.ui.adapter.ShoppingGuidePageAdapter;
import com.jz.community.moduleshoppingguide.home.ui.view.ChannelOutView;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.kingja.loadsir.core.Transport;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ChannelOutActivity extends BaseMvpActivity<ChannelOutView.View, ChannelOutPresenter> implements ChannelOutView.View, OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {


    @BindView(R2.id.channel_out_back)
    ImageView channelOutBack;
    @BindView(R2.id.channel_out_title)
    TextView channelOutTitle;
    @BindView(R2.id.channel_out_search)
    ImageView channelOutSearch;
    @BindView(R2.id.channel_out_toolbar)
    Toolbar channelOutToolbar;
    @BindView(R2.id.channel_out_comprehensive_btn)
    TextView channelOutComprehensiveBtn;
    @BindView(R2.id.channel_out_price_tv)
    TextView channelOutPriceTv;
    @BindView(R2.id.channel_out_price_iv)
    ImageView channelOutPriceIv;
    @BindView(R2.id.channel_out_price_btn)
    LinearLayout channelOutPriceBtn;
    @BindView(R2.id.channel_out_sale_tv)
    TextView channelOutSaleTv;
    @BindView(R2.id.channel_out_sale_iv)
    ImageView channelOutSaleIv;
    @BindView(R2.id.channel_out_sale_btn)
    LinearLayout channelOutSaleBtn;
    @BindView(R2.id.channel_out_new_btn)
    TextView channelOutNewBtn;
    @BindView(R2.id.channel_out_type_rv)
    RecyclerView channelOutTypeRv;
    @BindView(R2.id.channel_out_goods_rv)
    RecyclerView channelOutGoodsRv;
    @BindView(R2.id.channel_out_refresh)
    SmartRefreshLayout channelOutRefresh;
    @BindView(R2.id.channel_out_parent)
    LinearLayout channelOutParent;
    private LoadService loadService;
    private String id;
    private String shopId;

    private View noDataView;
    private View errorView;
    private View loadingView;

    private List<ChunnelTypeBean> type_list = new ArrayList<>();
    private OutGoodsTypeAdapter adapterType;
    private int oldPosition = 0;
    private String typeId;
    private String sort = "";

    private int page = 0;
    private int size = 10;
    private int totalPage = 0;
    private ShoppingGuidePageAdapter adapterGoods;
    private List<CategoriesGoodsBean.EmbeddedBeanXX.LinkedHashMapsBean> goods_list = new ArrayList<>();

    private int priceUpOrDown = 1;//0 箭头向上（降序） 1 箭头向下（升序）
    private int saleUpOrDown = 0;//0 箭头向上（降序） 1 箭头向下（升序）

    @Override
    protected int getContentView() {
        return R.layout.module_shoppingguide_activity_channel_out;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected ChannelOutPresenter createPresenter() {
        return new ChannelOutPresenter(this);
    }

    @Override
    protected void initView() {
        super.initView();
        ImmersionBar.with(this)
                .titleBar(channelOutToolbar)
                .statusBarDarkFont(true, 0.2f)//当白色背景状态栏遇到不能改变状态栏字体为深色的设备时，解决方案
                .init();

        id = getIntent().getStringExtra("id");
        shopId = getIntent().getStringExtra("shopId");


        if (getIntent().hasExtra("name")) {
            String title_name = getIntent().getStringExtra("name");
            channelOutTitle.setText(title_name);
        } else {
            channelOutTitle.setText("");
        }

        loadService = LoadSir.getDefault().register(channelOutParent, (Callback.OnReloadListener) v -> {
            if (loadService.getCurrentCallback() == ErrorCallback.class) {
                loadService.showCallback(LoadingCallback.class);
                RegionsBean.EmbeddedBean.ContentBean region = BaseSpUtils.getInstance().getRegion(mActivity);
                if (region != null) {
                    mPresenter.getChunnelCategories(id, region.getId() + "");
                }
            }

        });

        loadService.setCallBack(EmptyCallback.class, (context, view) -> {
            ImageView mIvEmpty = (ImageView) view.findViewById(R.id.empty_img);
            TextView mTvEmpty = (TextView) view.findViewById(R.id.empty_tv);
            mIvEmpty.setImageResource(R.mipmap.empty_default);
            mTvEmpty.setText("暂无商品！");
        });

        loadService.setCallBack(ErrorCallback.class, (context, view) -> {
            ImageView mIvError = (ImageView) view.findViewById(R.id.error_img);
            mIvError.setImageResource(R.mipmap.error_default);
        });

        loadService.setCallBack(LoadingCallback.class, new Transport() {
            @Override
            public void order(Context context, View view) {
                ImageView mIvLoading = (ImageView) view.findViewById(R.id.loading_img);
                GlideApp.with(mActivity)
                        .asGif()
                        .load(R.drawable.loading_default)
                        .into(mIvLoading);

            }
        });

        channelOutComprehensiveBtn.setEnabled(false);//进来默认选中“综合”，所以不能点击
        channelOutComprehensiveBtn.setTextColor(getResources().getColor(R.color.home_red));
        initTypeView();
        initGoodsView();
    }

    @Override
    protected void initDatas() {
        super.initDatas();
        RegionsBean.EmbeddedBean.ContentBean region = BaseSpUtils.getInstance().getRegion(this);
        if (region != null) {
            mPresenter.getChunnelCategories(id, region.getId() + "");
        }
    }

    private void initTypeView() {
        LinearLayoutManager time_layoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.HORIZONTAL, false);
        channelOutTypeRv.setHasFixedSize(true);
        channelOutTypeRv.setFocusable(false);
        channelOutTypeRv.setLayoutManager(time_layoutManager);
        adapterType = new OutGoodsTypeAdapter(R.layout.module_shoppingguide_item_out_type, type_list);
        adapterType.openLoadAnimation(BaseQuickAdapter.ALPHAIN);//加载动画
        channelOutTypeRv.setAdapter(adapterType);

        adapterType.setOnItemClickListener((adapter, view, position) -> {
            if (position != oldPosition) {
                adapterType.change(oldPosition, position);

                oldPosition = position;
                typeId = adapterType.getData().get(position).getId();
                if (null != adapterGoods) {
                    adapterGoods.replaceData(new ArrayList<>());
                    adapterGoods.setEmptyView(loadingView);
                }
                page = 0;
                mPresenter.getOutGoodsInfo(typeId, shopId, sort, page, size);

            }

        });

    }

    private void initGoodsView() {
        noDataView = getLayoutInflater().inflate(R.layout.view_empty, (ViewGroup) channelOutGoodsRv.getParent(), false);

        ImageView empty_iv = (ImageView) noDataView.findViewById(R.id.empty_img);
        TextView empty_tv = (TextView) noDataView.findViewById(R.id.empty_tv);

        empty_iv.setImageResource(R.mipmap.empty_default);
        empty_tv.setText("暂无商品！");

        errorView = getLayoutInflater().inflate(R.layout.view_error, (ViewGroup) channelOutGoodsRv.getParent(), false);

        ImageView error_iv = (ImageView) errorView.findViewById(R.id.error_img);
        error_iv.setImageResource(R.mipmap.error_default);

        loadingView = getLayoutInflater().inflate(R.layout.view_loading, (ViewGroup) channelOutGoodsRv.getParent(), false);

        ImageView loading_iv = (ImageView) loadingView.findViewById(R.id.loading_img);
        GlideApp.with(mActivity)
                .asGif()
                .load(R.drawable.loading_default)
                .into(loading_iv);

        GridLayoutManager main_layoutManager = new GridLayoutManager(mActivity, 2);
        channelOutGoodsRv.setHasFixedSize(true);
        channelOutGoodsRv.setFocusable(false);
        channelOutGoodsRv.setLayoutManager(main_layoutManager);
        channelOutRefresh.setEnableLoadMore(false);
        channelOutRefresh.setOnRefreshListener(this);

        adapterGoods = new ShoppingGuidePageAdapter(R.layout.module_shoppingguide_item_shopping_guide, goods_list);
        adapterGoods.openLoadAnimation(BaseQuickAdapter.ALPHAIN);//加载动画
        adapterGoods.setLoadMoreView(new CardLoadMoreView());
        adapterGoods.setOnLoadMoreListener(this, channelOutGoodsRv);
        channelOutGoodsRv.setAdapter(adapterGoods);

        errorView.setOnClickListener(v -> {
            page = 1;
            adapterGoods.setEmptyView(loadingView);
            mPresenter.getOutGoodsInfo(typeId, shopId, sort, page, size);
        });

        adapterGoods.setOnItemClickListener((adapter, view, position) -> RouterCommonUtils.startParameterActivity(RouterIntentConstant.MODULE_SHOPPING_GOODS_DETAIL, "url", adapterGoods.getData().get(position).get_links().getSelf().getHref()));

    }

    @Override
    public void showChannel(List<ChunnelTypeBean> entity) {
        if (entity != null) {
            type_list = entity;
            if (type_list.size() > 0) {
                loadService.showSuccess();
                adapterType.setNewData(type_list);
                oldPosition = 0;
                adapterType.getData().get(oldPosition).setSelect(true);
                typeId = adapterType.getData().get(oldPosition).getId();
                adapterGoods.setEmptyView(loadingView);
                mPresenter.getOutGoodsInfo(typeId, shopId, sort, page, size);
            } else {
                loadService.showCallback(EmptyCallback.class);

            }
        }

    }

    @Override
    public void showOutGoodsInfo(CategoriesGoodsBean entity) {
        finishRefresh();
        //总页数
        totalPage = entity.getPage().getTotalPages();

        if (totalPage <= 0) {
            //先设置空布局
            if (page == 0) {
                adapterGoods.replaceData(new ArrayList<>());
                adapterGoods.setEmptyView(noDataView);
                adapterGoods.notifyDataSetChanged();
            } else {
                adapterGoods.setEmptyView(noDataView);
                adapterGoods.notifyDataSetChanged();
            }
        } else {
            if (entity.get_embedded() != null && entity.get_embedded().getContent() != null) {
                goods_list = entity.get_embedded().getContent();
                if (page == 0) {
                    adapterGoods.setNewData(goods_list);
                    //如果数据少 不显示已加载全部
                    adapterGoods.disableLoadMoreIfNotFullPage();
                } else {
                    adapterGoods.addData(goods_list);

                }
            }

        }

        adapterGoods.loadMoreComplete();

    }

    @Override
    public void showChannelError(String s) {
        loadService.showCallback(ErrorCallback.class);

    }

    @Override
    public void showOutGoodsError(String s) {
        finishRefresh();
        adapterGoods.setEmptyView(errorView);
        adapterGoods.loadMoreFail();

    }

    private void selectChangeGoods() {
        if (null != adapterGoods) {
            adapterGoods.replaceData(new ArrayList<>());
            adapterGoods.setEmptyView(loadingView);
        }
        page = 0;
        mPresenter.getOutGoodsInfo(typeId, shopId, sort, page, size);

    }

    private void finishRefresh() {
        channelOutRefresh.finishRefresh(200);
    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        if (null != adapterGoods) {
            adapterGoods.setEnableLoadMore(false);
            adapterGoods.replaceData(new ArrayList<>());
            adapterGoods.setEmptyView(loadingView);
        }
        page = 0;
        mPresenter.getOutGoodsInfo(typeId, shopId, sort, page, size);
        adapterGoods.setEnableLoadMore(true);

    }

    @Override
    public void onLoadMoreRequested() {
        channelOutRefresh.setEnableRefresh(false);
        if (totalPage > 0) {
            if (page < totalPage - 1) {
                page++;
                mPresenter.getOutGoodsInfo(typeId, shopId, sort, page, size);
                channelOutRefresh.setEnableRefresh(true);
            } else {
                adapterGoods.loadMoreEnd();
                channelOutRefresh.setEnableRefresh(true);
            }
        }

    }

    @OnClick(R2.id.channel_out_back)
    public void backClick(View view) {
        finish();
    }

    @OnClick(R2.id.channel_out_search)
    public void searchClick(View view) {
        RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.SEARCH);
    }

    @OnClick(R2.id.channel_out_comprehensive_btn)
    public void comClick(View view) {
        //综合
        channelOutComprehensiveBtn.setEnabled(false);
        channelOutComprehensiveBtn.setTextColor(getResources().getColor(R.color.home_red));

        //价格变更
        priceUpOrDown = 1;//当点击到其他时，再点击价格选项，要置为向上箭头
        channelOutPriceTv.setTextColor(getResources().getColor(R.color.font_black));
        channelOutPriceIv.setImageResource(R.mipmap.sr_normal);
        channelOutPriceBtn.setEnabled(true);

        //销量变更
        saleUpOrDown = 0;//当点击到其他时，再点击销量选项，要置为向下箭头
        channelOutSaleTv.setTextColor(getResources().getColor(R.color.font_black));
        channelOutSaleIv.setImageResource(R.mipmap.sr_normal);
        channelOutSaleBtn.setEnabled(true);

        //上新变更
        channelOutNewBtn.setTextColor(getResources().getColor(R.color.font_black));
        channelOutNewBtn.setEnabled(true);

        sort = "";
        selectChangeGoods();
    }

    @OnClick(R2.id.channel_out_price_btn)
    public void priceClick(View view) {
        //价格
        channelOutPriceTv.setTextColor(getResources().getColor(R.color.home_red));
        if (priceUpOrDown == 0) {
            priceUpOrDown = 1;
            sort = "pricedesc";
            channelOutPriceIv.setImageResource(R.mipmap.sr_down);
            selectChangeGoods();
        } else {
            priceUpOrDown = 0;
            sort = "priceasc";
            channelOutPriceIv.setImageResource(R.mipmap.sr_up);
            selectChangeGoods();
        }

        //综合变更
        channelOutComprehensiveBtn.setTextColor(getResources().getColor(R.color.font_gary));
        channelOutComprehensiveBtn.setEnabled(true);

        //销量变更
        saleUpOrDown = 0;//当点击到其他时，再点击销量选项，要置为向下箭头
        channelOutSaleTv.setTextColor(getResources().getColor(R.color.font_black));
        channelOutSaleIv.setImageResource(R.mipmap.sr_normal);
        channelOutSaleBtn.setEnabled(true);

        //上新变更
        channelOutNewBtn.setTextColor(getResources().getColor(R.color.font_black));
        channelOutNewBtn.setEnabled(true);
    }

    @OnClick(R2.id.channel_out_sale_btn)
    public void saleClick(View view) {
        //销量
        channelOutSaleTv.setTextColor(getResources().getColor(R.color.home_red));
        if (saleUpOrDown == 0) {
            saleUpOrDown = 1;
            sort = "saledesc";
            channelOutSaleIv.setImageResource(R.mipmap.sr_down);
            selectChangeGoods();
        } else {
            saleUpOrDown = 0;
            sort = "saleasc";
            channelOutSaleIv.setImageResource(R.mipmap.sr_up);
            selectChangeGoods();
        }

        //综合变更
        channelOutComprehensiveBtn.setTextColor(getResources().getColor(R.color.font_gary));
        channelOutComprehensiveBtn.setEnabled(true);

        //价格变更
        priceUpOrDown = 1;//当点击到其他时，再点击价格选项，要置为向上箭头
        channelOutPriceTv.setTextColor(getResources().getColor(R.color.font_black));
        channelOutPriceIv.setImageResource(R.mipmap.sr_normal);
        channelOutPriceBtn.setEnabled(true);

        //上新变更
        channelOutNewBtn.setTextColor(getResources().getColor(R.color.font_black));
        channelOutNewBtn.setEnabled(true);
    }

    @OnClick(R2.id.channel_out_new_btn)
    public void newClick(View view) {
        //上新
        channelOutNewBtn.setEnabled(false);
        channelOutNewBtn.setTextColor(getResources().getColor(R.color.home_red));

        //综合变更
        channelOutComprehensiveBtn.setTextColor(getResources().getColor(R.color.font_black));
        channelOutComprehensiveBtn.setEnabled(true);

        //价格变更
        priceUpOrDown = 1;//当点击到其他时，再点击价格选项，要置为向上箭头
        channelOutPriceTv.setTextColor(getResources().getColor(R.color.font_black));
        channelOutPriceIv.setImageResource(R.mipmap.sr_normal);
        channelOutPriceBtn.setEnabled(true);

        //销量变更
        saleUpOrDown = 0;//当点击到其他时，再点击销量选项，要置为向下箭头
        channelOutSaleTv.setTextColor(getResources().getColor(R.color.font_black));
        channelOutSaleIv.setImageResource(R.mipmap.sr_normal);
        channelOutSaleBtn.setEnabled(true);

        sort = "createddesc";
        selectChangeGoods();
    }
}
